package org.diysearch.tools;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public abstract class XmlTools {
	private static final Log LOG = LogFactory.getLog(XmlTools.class);
	
	public static String getComment(String xml) throws Exception {
		XMLStreamReader parser = getParser(xml);
		boolean run = true;
		String content = null;
		while (run) {
			int event = parser.next();
			switch (event) {
			case XMLStreamConstants.END_DOCUMENT:
				parser.close();
				run = false;
				break;
			case XMLStreamConstants.COMMENT:
				content = parser.getText();
			}
		}
		return content;
	}
	
	public static List<String> getGroup (String xml) throws Exception {
		boolean run = true;
		XMLStreamReader parser = getParser(xml);
		List<String> groups = new ArrayList<String>();
		
		Document d = getDocument(xml);
		Element root = d.getRootElement();
		Element simpleOutput = root.getChild("CalaisSimpleOutputFormat");
		List<Element> children = simpleOutput.getChildren();

		for (Element child : children) {
			groups.add(child.getText());
		}
		
		return groups;
	}
	
	private static XMLStreamReader getParser(String xml) throws Exception {
		XMLInputFactory factory = XMLInputFactory.newInstance();
		return factory.createXMLStreamReader(new StringReader(xml));
	}
	
	private static Document getDocument (String xml) throws Exception {
		return new SAXBuilder().build(new StringReader(xml));
	}
}
